package com.jinxin.platform.cdacsrecord.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.cdacsrecord.core.mapper.JurenAcsOpenRecordMapper;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.JurenAcsCaptureRecord;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.JurenAcsOpenRecord;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.JurenOpenRecordInfo;
import com.jinxin.platform.cdacsrecord.core.pojo.domains.OpenRecordParam;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.CommonCodeEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.Constant;
import com.jinxin.platform.cdacsrecord.core.pojo.entity.ResultEntity;
import com.jinxin.platform.cdacsrecord.core.pojo.vo.DataResult2;
import com.jinxin.platform.cdacsrecord.core.redis.RedisUtil;
import com.jinxin.platform.cdacsrecord.core.service.JurenAcsOpenRecordService;
import com.jinxin.platform.cdacsrecord.core.service.RestTemplateService;
import com.jinxin.platform.cdacsrecord.core.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-08-28
 * @Author: Lingnan
 **/
@Service
public class JurenAcsOpenRecordServiceImpl implements JurenAcsOpenRecordService {

    @Autowired
    private JurenAcsOpenRecordMapper openRecordMapper;
    @Autowired
    private RestTemplateService restTemplateService;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public int insert(JurenAcsOpenRecord record) {
        return openRecordMapper.insert(record);
    }

    @Override
    public int updateByKey(JurenAcsOpenRecord record) {
        return openRecordMapper.updateByKey(record);
    }

    @Override
    public JurenAcsOpenRecord selectByKey(String id) {
        return openRecordMapper.selectByKey(id);
    }

    @Override
    public List<JurenAcsOpenRecord> listPage(HashMap param) {
        return openRecordMapper.listPage(param);
    }

    @Override
    public int listPageCount(HashMap param) {
        return openRecordMapper.listPageCount(param);
    }

    @Override
    public List listTimeCountData(HashMap param){
        return openRecordMapper.listTimeCountData(param);
    }

    @Override
    public ResultEntity updateData(String companyId,String startDate, String endDate) {
        if(StringUtils.isEmpty(companyId)){
            return new ResultEntity(CommonCodeEntity.PARAM_ERR,"小区不存在，数据更新失败","" );
        }
        OpenRecordParam param = new OpenRecordParam();
        param.setPage(1);
        int rows = 300;
        // 根据相差分钟数来定获取的条数 按照1分钟1次
        // 如果分页查询会有问题，其中的一些请求可能失败
        if(!StringUtils.isEmpty(startDate) && !StringUtils.isEmpty(endDate)){
            rows = (int) (DateUtil.dateDiffMin(startDate,endDate));
        }
        param.setRows(rows);
        param.setStartDate(startDate);
        param.setEndDate(endDate);
        ResultEntity resultEntity = restTemplateService.listOpenRecord(param,companyId);
        if(resultEntity != null && "000".equals(resultEntity.getResultCode())){
            DataResult2 dataResult = (DataResult2)resultEntity.getResultContent();
            JSONArray jsonArray = dataResult != null ? dataResult.getRows() : null;
            int count = 0;
            if(jsonArray != null && jsonArray.size() > 0){
                HashMap param2 = new HashMap();
                param2.put("startDate",startDate);
                param2.put("endDate",endDate);
                param2.put("companyId",companyId);
                List<JurenAcsOpenRecord> list = openRecordMapper.list(param2);
                List<String> idList = new ArrayList<>();
                for (JurenAcsOpenRecord record : list) {
                    idList.add(record.getOdId());
                }
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    JurenOpenRecordInfo info = JSON.parseObject(JSON.toJSONString(jsonObject), JurenOpenRecordInfo.class);
                    if(info != null){
                        JurenAcsOpenRecord record = openRecordMapper.selectByKey(info.getOdId());
                        if(record == null){
                            record = new JurenAcsOpenRecord();
                            JSONObject wyUserJson = info.getWyUser();
                            if(wyUserJson != null){
                                String wyUserId = wyUserJson.getString("wyUserId");
                                record.setWyUserId(wyUserId);
                                String wyUserName = wyUserJson.getString("wyUserName");
                                record.setWyUserName(wyUserName);
                                Integer wyUserType = wyUserJson.getInteger("wyUserType");
                                record.setWyUserType(wyUserType);
                            }
                            record.setOdId(info.getOdId());
                            record.setGateLocakName(info.getGateLockName());
                            record.setOpenType(info.getOpenType());
                            LocalDateTime createTime = DateUtil.getDateTimeOfTimestamp(info.getCreateTime());
                            //最新的时间作为下次同步的开始时间
                            if(i == 0){
                                String key = Constant.MODULE_PREX + "latest_open_record_time";
                                redisUtil.set(key,DateUtil.transTimeToString(createTime));
                            }
                            record.setCreateTime(createTime);
                            record.setCompletePicUrl(info.getCompletePicUrl());
                            record.setCompleteAssistantPicUrl(info.getCompleteAssistantPicUrl());
                            JSONObject gateLockJson = info.getGateLock();
                            if(gateLockJson != null){
                                JSONObject areaJson = JSON.parseObject(gateLockJson.get("buildingArea").toString());
                                if(areaJson != null){
                                    Integer areaId = areaJson.getInteger("areaId");
                                    record.setAreaId(String.valueOf(areaId));
                                }
                            }
                            record.setCompanyId(companyId);
                            openRecordMapper.insert(record);
                            count++;
                        }else {
                            idList.remove(info.getOdId());
                        }
                    }
                }
                // 删除不存在数据
                for (String id : idList) {
                    openRecordMapper.deleteByKey(id);
                }
            }
            return new ResultEntity(CommonCodeEntity.SUC_CODE,"成功同步"+count+"条开门记录","");
        }
        return new ResultEntity(CommonCodeEntity.FAIL,resultEntity.getResultDesc(),"" );
    }
}
